#include "savedatathread.h"
#include <QFile>
#include <QTextStream>
#include <QDateTime>

SaveDataThread::SaveDataThread(const QVector<QVector<double>> &data,
                               const QStringList &headers,
                               const QString &fileName,
                               QObject *parent)
    : QThread(parent)
    , m_data(data)
    , m_headers(headers)
    , m_fileName(fileName)
{
}

void SaveDataThread::run()
{
    // 检查文件是否可以打开
    QFile file(m_fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        emit saveFailed("无法打开文件: " + m_fileName);
        return;
    }

    QTextStream out(&file);
    out.setCodec("UTF-8");

    // 写入表头
    if (!m_headers.isEmpty()) {
        for (int i = 0; i < m_headers.size(); ++i) {
            out << m_headers[i];
            if (i < m_headers.size() - 1) {
                out << ",";
            }
        }
        out << "\n";
    }

    // 写入数据
    int rowCount = m_data.isEmpty() ? 0 : m_data[0].size();
    for (int row = 0; row < rowCount; ++row) {
        for (int col = 0; col < m_data.size(); ++col) {
            if (row < m_data[col].size()) {
                out << m_data[col][row];
            }
            if (col < m_data.size() - 1) {
                out << ",";
            }
        }
        out << "\n";
    }

    file.close();
    emit saveSuccess();
}
